package com.zpark.controller;

import com.zpark.utills.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RequestMapping("/upload")
@Controller
@Slf4j
public class UploadFileController {
    @RequestMapping("/files")
    public String toUpload(){
        return "uploads/uploadfiles";
    }
    @RequestMapping("/startUpload")
    public String upload(@RequestParam("myFile") MultipartFile file, Model model) {
        if (file.isEmpty()) {
            new RuntimeException("未找到文件");
        }
        // 获取源文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffixName = StringUtils.getSuffixName(fileName);
        System.out.println("文件后缀名:" + suffixName);
        // 获取随机字符串
        String newFileName = StringUtils.randomFileName();
        System.out.println("随机字符串:" + newFileName);
        // 确定存储位置
        String path = "D://tmp//";

        // 拼接绝对名称
        String uploadPathFile = path + newFileName + suffixName;
        // 判断路径是否存在
        File dest = new File(uploadPathFile);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            // 进行文件上传
            file.transferTo(dest);
            model.addAttribute("fileName", "/tmp/" + newFileName + suffixName);
            return "uploads/showFile";
        } catch (IOException e) {
            e.printStackTrace();
            log.debug("文件上传失败:" + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}